package com.runen.wnhz.runen.ui.activity.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.login.Wx.WXCallBack;
import com.runen.wnhz.runen.common.login.Wx.WeiXinUtils;
import com.runen.wnhz.runen.common.login.Wx.WxLoginInfo;
import com.runen.wnhz.runen.common.login.Wx.WxLoginUserInfo;
import com.runen.wnhz.runen.common.utils.ACache;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.Constants;
import com.runen.wnhz.runen.common.utils.JumpUtlis;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.GetTokenResponse;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerLoginComponent;
import com.runen.wnhz.runen.di.module.LoginModule;
import com.runen.wnhz.runen.presenter.Contart.LoginContart;
import com.runen.wnhz.runen.presenter.iPresenter.ILoginPersenter;
import com.runen.wnhz.runen.ui.ActivityManager;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.main.MainActivity;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.smarttop.library.utils.LogUtil;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * Created by Administrator on 2018-04-09.
 * 登陆模块
 */

public class LoginForPersonalActivity extends BaseActivity<ILoginPersenter> implements LoginContart.View, View.OnClickListener {
    @BindView(R.id.tv_skip)
    //跳过
            TextView tv_skip;
    //返回
    @BindView(R.id.iv_back)
    ImageView iv_back;
    //注册
    @BindView(R.id.tv_register)
    TextView tv_register;

    //手机号码输入框
    @BindView(R.id.et_input_phone)
    EditText et_input_phone;
    //密码输入框
    @BindView(R.id.et_input_password)
    EditText et_input_password;
    //验证码登陆按钮
    @BindView(R.id.tv_login_verification)
    TextView tv_login_verification;
    //忘记密码按钮
    @BindView(R.id.tv_forget_password)
    TextView tv_forget_password;

    //密码不正确，请重新输入
    @BindView(R.id.tv_pass_error)
    TextView tv_pass_error;


    //登陆按钮
    @BindView(R.id.tv_login)
    TextView tv_login;

    //微信登录
    @BindView(R.id.iv_login_wx)
    ImageView iv_login_wx;
    //QQ登陆
    @BindView(R.id.iv_login_qq)
    ImageView iv_login_qq;

    private WxLoginUserInfo mWxLoginUserInfo;
    private Map<String, Object> getTokenMap;

    private static Tencent mTencent;
    private UserInfo mInfo;
    private static boolean isServerSideLogin = false;

    private String type;

    @Override
    protected int getLayoutView() {
        return R.layout.login_for_personal_activty_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        setToolBarVisible(View.GONE);
    }

    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        JPushInterface.deleteAlias(this, Constants.JPUSH_SEQUEENS);
        //onClick
        initOnClick();
        getTokenMap = new HashMap<>();
    }

    private void initOnClick() {
        tv_skip.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        tv_register.setOnClickListener(this);
        tv_login_verification.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        iv_login_wx.setOnClickListener(this);
        iv_login_qq.setOnClickListener(this);


    }


    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerLoginComponent.builder().applicationComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build().initJect(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_skip:
                ACacheUtlis.getInstance().IsFirstToApp(this, Constants.ISFIRSTOAPP);
                JumpUtlis.getInstance().jumpActivity(this, MainActivity.class);
                break;
            case R.id.iv_back:
                ActivityManager.getAppManager().finishActivity(this);
                break;
            case R.id.tv_register:
                //跳转到注册页面
                Bundle bundle = getIntent().getBundleExtra("bundle");
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
                break;
            case R.id.tv_login_verification:
                JumpUtlis.getInstance().jumpActivity(this, VerificationActivity.class);
                break;
            case R.id.tv_forget_password:
                JumpUtlis.getInstance().jumpActivity(this, ForgetActivity.class);
                break;
            case R.id.tv_login:
                mPresenter.requesteName(false);
                break;
            case R.id.iv_login_wx:
                type = "1";
                WeiXinUtils.getInstance().regToWx(mContext);
                WxLoginInfo info = ACacheUtlis.getInstance().getWxInfo(mContext);

                WeiXinUtils.getInstance()
                        .wxLogin(this, info.getAccess_token(), info.getOpenid(), info.getRefresh_token())
                        .setWxCallBack(new WXCallBack() {
                            @Override
                            public void saveLoginInfo(  WxLoginInfo info) {
                                ACacheUtlis.getInstance().saveWxInfoToken(mContext,info.getAccess_token(),info.getOpenid(),info.getRefresh_token());
                              /*  ACacheUtlis.getInstance().saveWxInfo(mContext, info.getAccess_token(), info.getOpenid(), info.getRefresh_token(),info.getHeadimg(),info.getNickname(),type);*/
                                ToastUtil.showToast("weixin登录");
                                ACacheUtlis.getInstance().CommingFrom("log");

//                                mPresenter.requesteName(true);
                               /* JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this,ChoiceIdentityActivity.class);
                                finish();*/
                            }

                            @Override
                            public void saveUserInfo(WxLoginUserInfo info) {
                                mWxLoginUserInfo = info;
                                ACacheUtlis.getInstance().saveWxInfoUserinfo(mContext, info.getHeadimgurl(),info.getNickname(),type);
                                JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this,ChoiceIdentityActivity.class);
                                finish();
//                                thirdLogin();
                            }
                        });
                break;
            case R.id.iv_login_qq:
                type = "2";
                 mTencent = Tencent.createInstance("1107748313", LoginForPersonalActivity.this);
                mTencent.login(this, "all", loginListener);

//                startActivity(new Intent(this,QQLoginActivity.class));
                break;
            default:
                ToastUtil.showToast("未知错误");
                break;
        }

    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }

    @Override
    public String mobile() {
        return null;
    }

    @Override
    public void mMobileError() {

    }

    @Override
    public String Jpush_rigistID() {
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        return rid;
    }

    @Override
    public String verify() {
        return null;
    }

    @Override
    public String type() {
        return type;
    }

    @Override
    public String re_type() {
        return null;
    }

    @Override
    public void showSend(String msg) {

    }

    @Override
    public TextView getTextSendOut() {
        return null;
    }

    @Override
    public String mobiLogName() {
        return et_input_phone.getText().toString().trim();
    }

    @Override
    public String mobiLogPass() {
        return et_input_password.getText().toString().trim();
    }

    @Override
    public void showLoginErrorMsg(String msg) {
        tv_login_verification.setVisibility(View.GONE);
        tv_pass_error.setVisibility(View.VISIBLE);
        tv_pass_error.setTextColor(getResources().getColor(R.color.text_orange));
        tv_pass_error.setText(msg);
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                tv_login_verification.setVisibility(View.VISIBLE);
                tv_pass_error.setVisibility(View.GONE);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    handler.sendEmptyMessage(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    @Override
    public void saveUserBean(final UserBean data) {
        if (data != null) {
            ACacheUtlis.getInstance().IsFirstToApp(this, Constants.ISFIRSTOAPP);
            ACacheUtlis.getInstance().isLogin(this, "true");
            ACacheUtlis.getInstance().IsRequstUser(this, data.getToken(), data.getUsername()
                    , data.getHead_img(), et_input_phone.getText().toString().trim());
            connectRongIM(data);
            String rid = JPushInterface.getRegistrationID(this);
            JPushInterface.setAlias(this, Constants.JPUSH_SEQUEENS, rid);
        }
    }

    @Override
    public void showLogin(String info) {
        JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this,ChoiceIdentityActivity.class);
    }

    @Override
    public String openid() {
        return  ACacheUtlis.getInstance().getWxInfo(this).getOpenid();
    }

    @Override
    public String imgurl() {
        return ACacheUtlis.getInstance().getWxInfo(this).getHeadimg();
    }

    @Override
    public String nickname() {
        return ACacheUtlis.getInstance().getWxInfo(this).getNickname();
    }

    /**
     * 连接融云通讯
     *
     * @param data 登录之后返回的数据
     */
    private void connectRongIM(final UserBean data) {
        if (!TextUtils.isEmpty(data.getToken())) {
            getTokenMap.put("userId", et_input_phone.getText().toString().trim());
            getTokenMap.put("name", data.getUsername());
            getTokenMap.put("portraitUri", data.getHead_img());
            reGetToken(getTokenMap);
//            RongIM.connect(data.getToken(), new RongIMClient.ConnectCallback() {
//
//                @Override
//                public void onTokenIncorrect() {
//                    LogUtil.i("connect", "onTokenIncorrect");
//                    getTokenMap.put("userId", et_input_phone.getText().toString().trim());
//                    getTokenMap.put("name", data.getUsername());
//                    getTokenMap.put("portraitUri", data.getHead_img());
//                    reGetToken(getTokenMap);
//                }
//
//                @Override
//                public void onSuccess(String s) {
//                    LogUtil.i("connect", "onSuccess userid:" + s);
//                    editor.putString(Constants.RongIMToken, data.getToken());
//                    editor.commit();
//                    JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this, MainActivity.class);
//                    finish();
//                }
//
//                @Override
//                public void onError(RongIMClient.ErrorCode errorCode) {
//                    LogUtil.i("connect", "onError errorcode:" + errorCode.getValue());
//                }
//            });
        }
    }

    //重新获取token
    private void reGetToken(Map<String, Object> getTokenMap) {
        mPresenter.getRongIMToken(getTokenMap);
    }

    @Override
    public String getResterPhone() {
        return null;
    }

    @Override
    public String getResterSendOut() {
        return null;
    }

    @Override
    public String getResterPassWord() {
        return null;
    }

    @Override
    public void showJump(String msg) {

    }

    @Override
    public Bundle getBundle() {
        return getIntent().getBundleExtra("bundle");
    }

    @Override
    public String getVerifPhone() {
        return null;
    }

    @Override
    public String getVerifCode() {
        return null;
    }

    @Override
    public void saveVerifData(UserBean data) {
        String rid = JPushInterface.getRegistrationID(this);
        JPushInterface.setAlias(this, Constants.JPUSH_SEQUEENS, rid);
    }

    @Override
    public void getRequestRE(String re) {

    }

    @Override
    public String getForgetPhone() {
        return null;
    }

    @Override
    public String getForgetPass() {
        return null;
    }

    @Override
    public String getForgetNewPass() {
        return null;
    }

    @Override
    public String getForgetCode() {
        return null;
    }

    @Override
    public void saveForData(UserBean data) {
        //保存数据  直接跳转到首页
        if (data != null) {
            ACacheUtlis.getInstance().IsFirstToApp(this, Constants.ISFIRSTOAPP);
            ACacheUtlis.getInstance().IsRequstUser(this, data.getToken(), data.getUsername(), data.getHead_img()
                    , et_input_phone.getText().toString().trim());
            ACacheUtlis.getInstance().isLogin(this, "true");
            connectRongIM(data);

        }
    }

    @Override
    public void getRongTokenSuc(GetTokenResponse result) {
        GetTokenResponse tokenResponse = (GetTokenResponse) result;
        final String token = tokenResponse.getToken();
        if (!TextUtils.isEmpty(token)) {
            editor.putString(Constants.RongIMToken, token);
            editor.commit();
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    LogUtil.i("zmz", "reToken Incorrect");
                }

                @Override
                public void onSuccess(String s) {
                    LogUtil.i("zmz", "onSuccess userid:" + s);
                    JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this, MainActivity.class);
                    finish();
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    LogUtil.i("zmz", "onError" + e.getMessage());
                }
            });
        }
    }


    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            Log.d("SDKQQAgentPref", "AuthorSwitch_SDK:" + SystemClock.elapsedRealtime());
            initOpenidAndToken(values);
//            String headimg = values.getString("NickName");

  /*          ACacheUtlis.getInstance().saveWxInfo(mContext, mTencent.getAccessToken(), mTencent.getOpenId(), mTencent.getAccessToken(),"","");
            isServerSideLogin = true;
            ToastUtil.showToast("QQ登录");
            ACacheUtlis.getInstance().CommingFrom("log");
            JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this,ChoiceIdentityActivity.class);
            finish();*/
            updateUserInfo();
            mPresenter.requesteName(true);
//            updateLoginButton();
        }
    };
    public static void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(com.tencent.connect.common.Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch(Exception e) {
        }
    }

    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new IUiListener() {

                @Override
                public void onError(UiError e) {

                }

                @Override
                public void onComplete(final Object response) {


                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    new Thread(){

                        @Override
                        public void run() {
                            JSONObject json = (JSONObject)response;
                            if(json.has("figureurl")){
                                Bitmap bitmap = null;
                                //                                    bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));

                                Message msg = new Message();
                                msg.obj = json;
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            }
                        }

                    }.start();
                }

                @Override
                public void onCancel() {

                }
            };
            mInfo = new UserInfo(this, mTencent.getQQToken());
            mInfo.getUserInfo(listener);

        } else {
        /*    mUserInfo.setText("");
            mUserInfo.setVisibility(android.view.View.GONE);
            mUserLogo.setVisibility(android.view.View.GONE);*/
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    /*   mUserInfo.setVisibility(android.view.View.VISIBLE);
                       mUserInfo.setText(response.getString("nickname"));*/
                }
            }else if(msg.what == 1){
                JSONObject obj = (JSONObject) msg.obj;
                try {
                    String headimg = obj.getString("figureurl_qq_1");
                    String nickname = obj.getString("nickname");
                    ACacheUtlis.getInstance().saveWxInfo(mContext, mTencent.getAccessToken(), mTencent.getOpenId(), mTencent.getAccessToken(),headimg,nickname,type);
                    isServerSideLogin = true;
                    ToastUtil.showToast("QQ授权登录");
                    ACacheUtlis.getInstance().CommingFrom("log");


                } catch (JSONException e) {
                    e.printStackTrace();
                }
              /*  mUserLogo.setImageBitmap(bitmap);
                mUserLogo.setVisibility(android.view.View.VISIBLE);*/
            }
        }

    };
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                ToastUtil.showToast("返回为空,授权登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                ToastUtil.showToast("返回为空,授权登录失败");
                return;
            }
            ToastUtil.showToast("授权登录成功");
            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject values) {
         /*   ACacheUtlis.getInstance().saveWxInfo(mContext, mTencent.getAccessToken(), mTencent.getOpenId(), mTencent.getAccessToken(),"","");
            isServerSideLogin = true;
            ToastUtil.showToast("QQ登录");
            ACacheUtlis.getInstance().CommingFrom("log");
            JumpUtlis.getInstance().jumpActivity(LoginForPersonalActivity.this,ChoiceIdentityActivity.class);
            finish();*/
        }

        @Override
        public void onError(UiError e) {
            ToastUtil.showToast("onError: " + e.errorDetail);
        }

        @Override
        public void onCancel() {
            ToastUtil.showToast("onCancel: ");
            if (isServerSideLogin) {
                isServerSideLogin = false;
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "-->onActivityResult " + requestCode  + " resultCode=" + resultCode);
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode,resultCode,data,loginListener);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
